package com.wl.eb.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wl.eb.mapper.EbProductMapper;
import com.wl.eb.module.EbProduct;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 用一句话描述
 * @Auther: 新梦想*陈超
 * @Date: 2021/12/6 08:45
 */
@Service//证
public class ProductService {
    @Resource
    private EbProductMapper ebProductMapper;
    public EbProduct detail(int productId){
        return ebProductMapper.selectById(productId);
    }

    public Page list(int psize,int categoryId){
        Page page = new Page(psize,12);
        Page productList = ebProductMapper.selectPage(page,new QueryWrapper<EbProduct>()
                .eq("epc_child_id",categoryId));
        return productList;
    }
    /**
     * 根据商品id将商品放入购物车(购物车表，session作为购物车)
     * @param id 商品id
     * @return
     */
    public void addCar(int id, HttpServletRequest request) {
        //1.根据id查询商品的所有信息
        EbProduct ebProduct = ebProductMapper.selectById(id);
        //2.购物车中（session）
        HttpSession session = request.getSession();
        //2.1.准备一个蛇皮袋 List
        List<EbProduct> productList = (List<EbProduct>)
                session.getAttribute("car");
        if(productList==null){
            productList = new ArrayList<>();
        }

        boolean flag =false;//假设不存在
        for (int i=0;i<productList.size();i++){
            if(productList.get(i).getEpId().equals(ebProduct.getEpId())){
                //新添加的商品在购物车中已经存在，则只需要将购物车中的商品数量+1
                productList.get(i).setCount(productList.get(i).getCount()+1);
                flag=true;
                break;
            }
        }

        //2.2.将商品放入蛇皮袋
        if (!flag) {
            productList.add(ebProduct);
        }

        //2.3将蛇皮袋放入购物车
        session.setAttribute("car",productList);
        System.out.println("放入购物车的商品为："+ebProduct);
    }


}
